package com.panghl.filter;

import com.panghl.domain.LoginUser;
import com.panghl.utils.JwtUtil;
import com.panghl.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义JWT认证过滤器
 * 该类继承自BasicAuthenticationFilter【OncePerRequestFilter子类】，在doFilterInternal方法中，
 * 从http头的Authorization 项读取token数据，然后用Jwts包提供的方法校验token的合法性。
 * 如果校验通过，就认为这是一个取得授权的合法请求
 * @author panghl on 2022/02/13.
 */
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        String redisKey = "login:"+userId;
        //从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(loginUser,
                        null,loginUser.getAuthorities()));

        filterChain.doFilter(request, response);
    }


    /**
     * 下面代码是RouYi拷贝过来的
     */
    //@Autowired
    //private TokenService tokenService;
    //
    //@Override
    //protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
    //        throws ServletException, IOException {
    //
    //    LoginUser loginUser = tokenService.getLoginUser(request);
    //    if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
    //        tokenService.verifyToken(loginUser);
    //        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
    //        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
    //        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    //    }
    //    chain.doFilter(request, response);
    //}
}
